﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Windows.Forms;
using System.Globalization;
using ArgusLib.Controls;

namespace Fraktalysator.Controls
{
	class PercentComboBox : ComboBox
	{
		ValueCheckerPercent valueChecker;

		public float Value
		{
			get { return this.valueChecker.Value; }
			set { this.valueChecker.Value = value; }
		}
		public event EventHandler ValueChanged
		{
			add { this.valueChecker.ValueChanged += value; }
			remove { this.valueChecker.ValueChanged -= value; }
		}

		public PercentComboBox()
			: base()
		{
			this.BackColor = Color.Black;
			this.ForeColor = Color.White;
			this.valueChecker = new ValueCheckerPercent(this);
		}
	}

	class ValueCheckerPercent : ValueChecker<float>
	{
		public ValueCheckerPercent(Control control)
			: base(control, null)
		{
			NumberFormatInfo nfi = NumberFormatInfo.CurrentInfo;
			StringBuilder sBuilder = new StringBuilder(nfi.NativeDigits.Length+3);
			foreach (string s in nfi.NativeDigits)
			{
				sBuilder.Append(s);
			}
			sBuilder.Append(nfi.PercentDecimalSeparator);
			sBuilder.Append(nfi.PercentGroupSeparator);
			sBuilder.Append(nfi.PercentSymbol);
			this.AllowedChars = CharSet.FromChars(sBuilder.ToString());
		}

		protected override bool ConvertFromString(string text, out float value)
		{
			string percent = NumberFormatInfo.CurrentInfo.PercentSymbol;

			if (text.Contains(percent) == false)
			{
				return float.TryParse(text, out value);
			}

			text.Trim();
			string[] parts = text.Split(new string[] { percent }, StringSplitOptions.RemoveEmptyEntries);
			if (parts.Length != 1)
			{
				value = 0;
				return false;
			}

			if (float.TryParse(parts[0], out value) == true)
			{
				value /= 100;
				return true;
			}

			return false;
		}

		protected override string ConvertToString(float value)
		{
			return value.ToString("p0");
		}
	}
}
